package com.mymarkdown.app.fx.event.hander.impl;

import com.mymarkdown.app.common.constant.Constant;
import com.mymarkdown.app.fx.annotation.KeyWord;
import com.mymarkdown.app.fx.enums.FxEventEnum;
import com.mymarkdown.app.fx.event.hander.KeyWordHandler;
import com.mymarkdown.app.fx.event.model.FxEvent;
import com.mymarkdown.app.interfaces.UserInfoService;
import com.mymarkdown.app.util.FileUtil;
import com.mymarkdown.app.websocket.enums.MessageTypeEnum;
import com.mymarkdown.app.websocket.interfaces.WebSocketSendMessage;
import com.mymarkdown.app.websocket.message.MessagePojo;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javafx.scene.input.Clipboard;
import javafx.scene.web.WebEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;

/**
 * @author zenglun
 * @date 2021/12/7 11:25 上午
 * @description: 处理图片插入事件，插入时应该先将判断当前是否有操作文件夹，如果没有,则应该将事件分发给保存事件处理,等待保存成功之后再进行写入文件
 */
@Slf4j
@Component
@KeyWord(FxEventEnum.INSET_IMAGE)
public class InsertImageEvenHandler implements KeyWordHandler {

    @Autowired
    private KeyWordHandler keyWordHandler;


    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private WebSocketSendMessage webSocketSendMessage;


    @Override
    public void handler(WebEngine engine, FxEvent event) {
        //直接帮你调用
        //将事件分发给其他的
        BlockingQueue<File> operationFile = userInfoService.getOperationFile();
        File file = operationFile.peek();
        if (Objects.isNull(file)){
            keyWordHandler.handler(engine, new FxEvent().setEventType(FxEventEnum.SAVE_MD));
        }
        //获取当前文件夹
        file =  operationFile.peek();
        if (Objects.isNull(file)){
            // 下发指令告诉用户失败了，没有保存相关的文件
            webSocketSendMessage.sendMessage(MessagePojo.empty().setMessageType(MessageTypeEnum.TISP_MSG.getMessageType())
                    .setBody("保存图片信息失败,请先保存当前文件!"));
            return;
        }

        //判断当前存放的文件
        File saveImageDir = new File(file.getParent() + "/images");

        if (!saveImageDir.exists()){
            saveImageDir.mkdirs();
        }

        try {
            Clipboard clipboard = Clipboard.getSystemClipboard();
            Image image = clipboard.getImage();
            if (Objects.isNull(image)){
                return;
            }
            BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
            if (Objects.isNull(bImage)){
                return;
            }
            //随机生成文件名
            String dateFileName = FileUtil.getDateFileName();
            File imageFile = new File(saveImageDir.getPath() + "/" + dateFileName + ".png");

            ImageIO.write(bImage, "png", imageFile);
            //写入成功之后，下发指令告诉客户端，向当前光标位置插入image,并显示
            String imagePath = String.format(Constant.BASE_IMAGE_PATH, imageFile.getPath());
            log.info("[InsertImageEvenHandler]---[handler],获取到的图片路径为:{}, 最终图片路径为:{}", imageFile.getPath(), imagePath);
            BlockingQueue<File> operationMdPdfFile = userInfoService.getOperationFile();
            File peek = operationMdPdfFile.peek();
            String showImagePath = imageFile.getPath();
            if (Objects.nonNull(peek)){
                showImagePath = showImagePath.replace(peek.getParent() + "/", "");
            }
            webSocketSendMessage.sendMessage(MessagePojo.empty().setMessageType(MessageTypeEnum.INSERT_IMAGE.getMessageType()).setBody(showImagePath));
        } catch (IOException e) {
            e.printStackTrace();
            // 写入文件失败
            log.error("[InsertImageEvenHandler]---[handler],写入图片发生异常异，常信息为:{}", e);
            webSocketSendMessage.sendMessage(MessagePojo.empty().setMessageType(MessageTypeEnum.TISP_MSG.getMessageType())
                    .setBody("保存图片信息失败!"));
        }
    }

    @Override
    public boolean afterHandler(WebEngine engine, FxEvent event) {
        return true;
    }

    @Override
    public void beforeHandler(WebEngine engine, FxEvent event) {

    }
}
